<template>
  <div class="chat-container">
    <!-- 添加设备状态面板 -->
    <div class="device-status">
      <div class="light-control">
        <div class="light-bulb" :class="{ 'light-on': lightStatus }">
          <el-icon :size="24">
            <component :is="lightStatus ? 'Sunny' : 'Moon'" />
          </el-icon>
        </div>
        <div class="light-status">
          状态: {{ lightStatus ? '开启' : '关闭' }}
        </div>
        <div class="light-buttons">
          <el-button type="success" size="small" @click="controlLight(true)" :disabled="lightStatus">
            开灯
          </el-button>
          <el-button type="warning" size="small" @click="controlLight(false)" :disabled="!lightStatus">
            关灯
          </el-button>
        </div>
      </div>

      <!-- 添加温度显示 -->
      <div class="temperature-display">
        <span class="temperature-value">{{ temperature.toFixed(1) }}°C</span>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-for="msg in messages" :key="msg.id" class="message-item" :class="{ 'message-user': msg.isUser }">
        <div class="message-content">
          {{ msg.content }}
        </div>
      </div>
    </div>
    <div class="chat-input">
      <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          placeholder="请输入消息..."
          @keyup.enter.exact.prevent="sendMessage"
      />
      <el-button
        type="primary"
        :icon="Microphone"
        :class="{ 'is-recording': isListening }"
        @mousedown="startVoiceInput"
        @mouseup="stopVoiceInput"
        @mouseleave="stopVoiceInput"
        @touchstart.prevent="startVoiceInput"
        @touchend.prevent="stopVoiceInput"
      >
        {{ isListening ? '松开结束' : '按住说话' }}
      </el-button>
      <el-button type="primary" :loading="loading" @click="sendMessage">
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, onUnmounted} from 'vue'
import request from '../api/request'
import { ElMessage } from 'element-plus'

const messages = ref([])
const loading = ref(false)
const userInput = ref('')
const messagesContainer = ref(null)

// 灯控制相关
const lightStatus = ref(false)
let ws = null

// 语音识别相关
const isListening = ref(false)
let recognition = null
let voiceTimer = null

// 添加温度状态
const temperature = ref(25)

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return

  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    content: userInput.value,
    isUser: true
  })

  loading.value = true

  try {
    // /v1/workspace/{slug}/thread/{threadSlug}/chat
    const data = await request.post('http://192.168.3.14:3001/api/v1/workspace/bd0cd7e2-5b8c-428b-b56a-2e0fc0df6635/thread/343636df-4548-41d6-a031-4ea07b38d4db/chat', {
          "message": '我说指令，请直接只返回url,' + userInput.value,
          "mode": "chat",
        }
    )

    let answer = data.textResponse?.includes('</think>') ? data.textResponse.split('</think>')[1] : data.textResponse
    // 添加AI响应
    messages.value.push({
      id: Date.now() + 1,
      content: answer, // data.textResponse.split('</think>')[1],
      isUser: false
    })
    debugger
    let url = answer.trim().split('`').find(i=>i.startsWith('http'))
    if(url.trim()){
      await request.post(url.trim())
    }
  } catch (error) {
    // 添加错误消息
    messages.value.push({
      id: Date.now() + 1,
      content: '抱歉，发生了错误，请稍后重试。',
      isUser: false
    })
  } finally {
    loading.value = false
    userInput.value = ''
    await nextTick()
    scrollToBottom()
  }
}

// 连接WebSocket
const connectWebSocket = () => {
  ws = new WebSocket('ws://192.168.3.14:5567')

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data)
    if (data.type === 'light') {
      lightStatus.value = data.status
    } else if (data.type === 'temperature') {
      temperature.value = data.value
    } else if (data.type === 'status') {
      // 处理完整状态更新
      lightStatus.value = data.lightStatus
      temperature.value = data.temperature
    }
  }

  ws.onclose = () => {
    // 尝试重连
    setTimeout(connectWebSocket, 1000)
  }
}

// 控制灯
const controlLight = async (status) => {
  try {
    await request.post(`http://192.168.3.14:5566/${status ? 'open' : 'close'}`)
  } catch (error) {
    console.error('控制灯失败:', error)
  }
}

// 开始语音输入
const startVoiceInput = async () => {
  try {
    // 每次都创建新的实例
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    if (!SpeechRecognition) {
      ElMessage.error('您的浏览器不支持语音识别功能')
      return
    }

    // 停止之前的实例
    if (recognition) {
      try {
        recognition.stop()
        recognition.onresult = null
        recognition.onerror = null
      } catch (e) {
        console.error('停止上一次录音失败:', e)
      }
    }

    // 创建新实例
    recognition = new SpeechRecognition()
    recognition.lang = 'zh-CN'
    recognition.continuous = true
    recognition.interimResults = true

    recognition.onresult = (event) => {
      console.log('onresult=========')
      const transcript = Array.from(event.results)
        .map(result => result[0].transcript)
        .join('')
      userInput.value = transcript
    }

    recognition.onerror = (event) => {
      console.log('onerrorxxxxxxxxxxxxxxxx')
      console.error('语音识别错误:', event.error)
      stopVoiceInput()
      ElMessage.error('语音识别失败，请重试')
    }

    // 短暂延迟确保上一次录音完全停止
    await new Promise(resolve => setTimeout(resolve, 100))

    recognition.start()
    isListening.value = true

    // 添加震动反馈（如果设备支持）
    if (navigator.vibrate) {
      navigator.vibrate(50)
    }

    // 最长录音时间限制
    if (voiceTimer) {
      clearTimeout(voiceTimer)
    }
    voiceTimer = setTimeout(() => {
      stopVoiceInput()
      ElMessage.warning('录音时间过长，已自动停止')
    }, 60000) // 60秒限制

  } catch (error) {
    console.error('启动语音识别失败:', error)
    ElMessage.error('启动语音识别失败，请重试')
    isListening.value = false
  }
}

// 停止语音输入
const stopVoiceInput = async () => {
  if (!recognition) return

  try {
    recognition.stop()
    recognition.onresult = null
    recognition.onerror = null
    recognition = null
    isListening.value = false

    // 清除计时器
    if (voiceTimer) {
      clearTimeout(voiceTimer)
      voiceTimer = null
    }

    // 添加震动反馈
    if (navigator.vibrate) {
      navigator.vibrate([50, 50, 50])
    }
  } catch (error) {
    console.error('停止语音识别失败:', error)
  } finally {
    isListening.value = false
  }
}

onMounted(() => {
  connectWebSocket()
  scrollToBottom()
})

onUnmounted(() => {
  if (recognition) {
    recognition.stop()
  }
  if (voiceTimer) {
    clearTimeout(voiceTimer)
  }
  if (ws) {
    ws.close()
  }
})
</script>

<style scoped>
.chat-container {
  height: 60vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  width: 500px;
  margin: auto;
  margin-top: 100px;
  border: 1px solid #ccc;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;

}

.message-item {
  margin: 10px 0;
  max-width: 80%;
}

.message-user {
  margin-left: auto;
}

.message-content {
  padding: 10px 15px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message-user .message-content {
  background-color: #409eff;
  color: white;
}

.chat-input {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.chat-input :deep(.el-textarea__inner) {
  resize: none;
}

/* 灯控制样式 */
.light-control {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: white;
}

.light-bulb {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  transition: all 0.3s;
}

.light-bulb.light-on {
  background-color: #ffd700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.5);
}

.light-status {
  flex: 1;
  text-align: center;
  margin: 0 15px;
}

.light-buttons {
  display: flex;
  gap: 10px;
}

/* 修改录音按钮样式 */
.is-recording {
  animation: pulse 1.5s infinite;
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 防止长按时出现系统菜单 */
.chat-input .el-button {
  min-width: 90px;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}

.device-status {
  background-color: white;
  border-bottom: 1px solid #eee;
}

.temperature-display {
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-top: 1px solid #eee;
}

.temperature-value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}
</style>
